<template>
    <div>
        <div class="container">
            <TableCustom 
                :columns="columns" 
                :tableData="menuData" 
                row-key="id" 
                :has-pagination="false"
                :loading="loading"
                :viewFunc="handleView" 
                :delFunc="handleDelete" 
                :editFunc="handleEdit"
            >
                <template #toolbarBtn>
                    <el-button type="warning" :icon="CirclePlusFilled" @click="handleAdd">新增</el-button>
                </template>
                <template #icon="{ rows }">
                    <el-icon v-if="isValidElementIcon(rows.icon)">
                        <component :is="ElementPlusIconsVue[rows.icon]"></component>
                    </el-icon>
                    <span v-else class="icon-text">{{ rows.icon || '-' }}</span>
                </template>
                <template #isDisplay="{ rows }">
                    <el-tag :type="rows.isDisplay === 1 ? 'success' : 'info'">
                        {{ formatDisplayStatus(rows.isDisplay) }}
                    </el-tag>
                </template>
                <template #status="{ rows }">
                    <el-tag :type="rows.status === 1 ? 'success' : 'danger'">
                        {{ formatStatus(rows.status) }}
                    </el-tag>
                </template>
                <template #createTime="{ rows }">
                    {{ formatTime(rows.createTime) }}
                </template>
            </TableCustom>
        </div>
        <el-dialog :title="isEdit ? '编辑菜单' : '新增菜单'" v-model="visible" width="700px" destroy-on-close
            :close-on-click-modal="false" @close="closeDialog">
            <el-form 
                ref="menuFormRef" 
                :model="rowData" 
                :rules="formRules" 
                label-width="100px"
                label-position="left"
            >
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="菜单名称" prop="menuName">
                            <el-input v-model="rowData.menuName" placeholder="请输入菜单名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="菜单编码" prop="menuCode">
                            <el-input v-model="rowData.menuCode" placeholder="请输入菜单编码" />
                        </el-form-item>
                    </el-col>
                </el-row>
                
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="路由路径">
                            <el-input v-model="rowData.url" placeholder="请输入路由路径" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="图标" prop="icon">
                            <el-input 
                                v-model="rowData.icon" 
                                placeholder="请选择图标" 
                                readonly
                                @click="showIconSelector = true"
                                style="cursor: pointer"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="排序" prop="sortOrder">
                            <el-input-number v-model="rowData.sortOrder" :min="1" :max="999" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="父菜单" prop="parentId">
                            <el-cascader 
                                v-model="parentMenuValue" 
                                :options="cascaderOptions" 
                                :props="{ 
                                    checkStrictly: true, 
                                    emitPath: false
                                }"
                                @change="handleParentMenuChange"
                                clearable 
                                placeholder="请选择父菜单"
                                style="width: 100%"
                                filterable
                                :show-all-levels="false"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="是否显示" prop="isDisplay">
                            <el-select v-model="rowData.isDisplay" placeholder="请选择" style="width: 100%">
                                <el-option label="显示" :value="1" />
                                <el-option label="隐藏" :value="0" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="closeDialog">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="loading">
                        {{ isEdit ? '更新' : '保存' }}
                    </el-button>
                </div>
                </template>
        </el-dialog>
        
        <!-- 图标选择器弹窗 -->
        <el-dialog title="选择图标" v-model="showIconSelector" width="800px" destroy-on-close>
            <div class="icon-selector">
                <div class="icon-search">
                    <el-input 
                        v-model="iconSearchText" 
                        placeholder="搜索图标" 
                        clearable
                        style="width: 200px"
                    />
                </div>
                <div class="icon-grid">
                    <div 
                        v-for="icon in filteredIcons" 
                        :key="icon"
                        class="icon-item"
                        :class="{ active: rowData.icon === icon }"
                        @click="selectIcon(icon)"
                    >
                        <el-icon size="24">
                            <component :is="ElementPlusIconsVue[icon]"></component>
                        </el-icon>
                        <span class="icon-name">{{ icon }}</span>
                    </div>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="showIconSelector = false">取消</el-button>
                    <el-button type="primary" @click="confirmIconSelection">确定</el-button>
                </div>
            </template>
        </el-dialog>
        
        <el-dialog title="查看详情" v-model="visible1" width="700px" destroy-on-close>
            <TableDetail :data="viewData">
                <template #icon="{ rows }">
                    <el-icon v-if="isValidElementIcon(rows.icon)">
                        <component :is="ElementPlusIconsVue[rows.icon]"></component>
                    </el-icon>
                    <span v-else class="icon-text">{{ rows.icon || '-' }}</span>
                </template>
            </TableDetail>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="system-menu">
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { CirclePlusFilled } from '@element-plus/icons-vue';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import { MenuItem, MenuRequest } from '@/types/menu';
import { getMenuTree, saveMenu, updateMenu, getMenuById, deleteMenu } from '@/api/system/menu';
import TableCustom from '@/components/table-custom.vue';
import TableDetail from '@/components/table-detail.vue';
import { formatTime } from '@/utils/time';

// 菜单数据
const menuData = ref<MenuItem[]>([]);
const loading = ref(false);

// 表格相关
let columns = ref([
    { prop: 'menuName', label: '菜单名称', align: 'left' },
    { prop: 'icon', label: '图标' },
    { prop: 'url', label: '路由路径' },
    { prop: 'menuCode', label: '菜单编码' },
    { prop: 'sortOrder', label: '排序', width: 80 },
    { prop: 'isDisplay', label: '是否显示', width: 100 },
    { prop: 'status', label: '状态', width: 100 },
    { prop: 'createTime', label: '创建时间', width: 180 },
    { prop: 'operator', label: '操作', width: 250, fixed: 'right' },
])

// 转换菜单数据为级联选择器格式
const getCascaderOptions = (data: MenuItem[]): any[] => {
    return data.map(item => {
        const option: any = {
            label: item.menuName,
            value: item.id,
        }
        if (item.children && item.children.length > 0) {
            option.children = getCascaderOptions(item.children);
        }
        return option;
    });
}

// 不再添加顶级选项，无父菜单时显示为空

// 父菜单选择器的值
const parentMenuValue = ref<string[]>([]);

// 监听父菜单选择变化
const handleParentMenuChange = (value: string | string[]) => {
    console.log('父菜单选择变化:', value);
    if (value && value !== '') {
        if (Array.isArray(value)) {
            rowData.value.parentId = value[value.length - 1]; // 取最后一个值作为父菜单ID
        } else {
            rowData.value.parentId = value;
        }
    } else {
        rowData.value.parentId = '0'; // 无父菜单时设为0
    }
    console.log('设置的父菜单ID:', rowData.value.parentId);
};

// 根据父菜单ID查找路径
const findParentPath = (menus: MenuItem[], targetId: string, currentPath: string[] = []): string[] => {
    for (const menu of menus) {
        const newPath = [...currentPath, menu.id];
        if (menu.id === targetId) {
            return newPath;
        }
        if (menu.children && menu.children.length > 0) {
            const result = findParentPath(menu.children, targetId, newPath);
            if (result.length > 0) {
                return result;
            }
        }
    }
    return [];
};

const cascaderOptions = ref<any[]>([]);

// 图标选择器相关
const showIconSelector = ref(false);
const iconSearchText = ref('');
const selectedIcon = ref('');

// Element Plus 图标列表
const iconList = Object.keys(ElementPlusIconsVue).filter(iconName => {
    // 过滤掉一些不常用的图标，保留主要的图标
    const excludeIcons = ['Loading', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'];
    return !excludeIcons.includes(iconName);
});

// 过滤后的图标列表
const filteredIcons = computed(() => {
    if (!iconSearchText.value) {
        return iconList;
    }
    return iconList.filter(icon => 
        icon.toLowerCase().includes(iconSearchText.value.toLowerCase())
    );
});

// 选择图标
const selectIcon = (icon: string) => {
    selectedIcon.value = icon;
};

// 确认图标选择
const confirmIconSelection = () => {
    if (selectedIcon.value) {
        rowData.value.icon = selectedIcon.value;
    }
    showIconSelector.value = false;
    selectedIcon.value = '';
    iconSearchText.value = '';
};

// 表单引用
const menuFormRef = ref();

// 表单验证规则
const formRules = {
    menuName: [
        { required: true, message: '请输入菜单名称', trigger: 'blur' },
        { min: 1, max: 50, message: '菜单名称长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    menuCode: [
        { required: true, message: '请输入菜单编码', trigger: 'blur' },
        { min: 1, max: 50, message: '菜单编码长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    // url: [
    //     { required: true, message: '请输入路由路径', trigger: 'blur' }
    // ],
    sortOrder: [
        { required: true, message: '请输入排序', trigger: 'blur' },
        { type: 'number', min: 1, max: 999, message: '排序必须在 1 到 999 之间', trigger: 'blur' }
    ],
    isDisplay: [
        { required: true, message: '请选择是否显示', trigger: 'change' }
    ]
};
const visible = ref(false);
const isEdit = ref(false);
const rowData = ref<MenuItem>({} as MenuItem);

// 获取菜单数据
const loadMenuData = async () => {
    try {
        loading.value = true;
        const res = await getMenuTree();
        const responseData = res as any;
        
        if (responseData && responseData.code === 200 && responseData.data) {
            menuData.value = responseData.data;
            // 更新级联选择器选项
            cascaderOptions.value = getCascaderOptions(responseData.data);
            console.log('菜单数据:', responseData.data);
            console.log('级联选择器选项:', cascaderOptions.value);
        } else {
            const errorMsg = (responseData && responseData.msg) || '获取菜单数据失败';
            ElMessage.error(errorMsg);
            menuData.value = [];
        }
    } catch (error) {
        console.error('获取菜单数据失败:', error);
        ElMessage.error('获取菜单数据失败，请稍后重试');
        menuData.value = [];
    } finally {
        loading.value = false;
    }
};

const handleEdit = async (row: MenuItem) => {
    try {
        loading.value = true;
        // 根据ID获取最新菜单详情
        const res = await getMenuById(row.id);
        const responseData = res as any;
        
        if (responseData && responseData.code === 200 && responseData.data) {
            rowData.value = { ...responseData.data };
            
            // 设置父菜单选择器的值
            if (responseData.data.parentId && responseData.data.parentId !== '0') {
                // 需要根据parentId找到对应的路径
                const parentPath = findParentPath(menuData.value, responseData.data.parentId);
                parentMenuValue.value = parentPath;
                console.log('编辑时设置的父菜单路径:', parentPath);
            } else {
                parentMenuValue.value = []; // 无父菜单时显示为空
                console.log('编辑时设置为无父菜单');
            }
            
    isEdit.value = true;
    visible.value = true;
        } else {
            const errorMsg = (responseData && responseData.msg) || '获取菜单详情失败';
            ElMessage.error(errorMsg);
        }
    } catch (error) {
        console.error('获取菜单详情失败:', error);
        ElMessage.error('获取菜单详情失败，请稍后重试');
    } finally {
        loading.value = false;
    }
};

// 表单提交处理
const handleSubmit = async () => {
    try {
        // 表单验证
        await menuFormRef.value.validate();
        
        loading.value = true;
        
        // 准备提交数据
        const submitData: MenuRequest = {
            parentId: rowData.value.parentId,
            menuName: rowData.value.menuName,
            menuCode: rowData.value.menuCode,
            url: rowData.value.url,
            sortOrder: rowData.value.sortOrder,
            icon: rowData.value.icon || '',
            isDisplay: rowData.value.isDisplay,
            description: '', // 固定为空
            status: 1 // 固定为启用状态
        };
        
        // 如果是编辑，添加ID
        if (isEdit.value) {
            submitData.id = rowData.value.id;
        }
        
        if (isEdit.value) {
            // 编辑菜单
            const res = await updateMenu(submitData);
            const responseData = res as any;
            if (responseData && responseData.code === 200) {
                ElMessage.success('菜单更新成功');
                closeDialog();
                loadMenuData();
            } else {
                const errorMsg = (responseData && responseData.msg) || '更新菜单失败';
                ElMessage.error(errorMsg);
            }
        } else {
            // 新增菜单
            const res = await saveMenu(submitData);
            const responseData = res as any;
            if (responseData && responseData.code === 200) {
                ElMessage.success('菜单创建成功');
    closeDialog();
                loadMenuData();
            } else {
                const errorMsg = (responseData && responseData.msg) || '创建菜单失败';
                ElMessage.error(errorMsg);
            }
        }
    } catch (error) {
        if (error !== false) { // 表单验证失败时 error 为 false
            console.error('保存菜单失败:', error);
            ElMessage.error('操作失败，请稍后重试');
        }
    } finally {
        loading.value = false;
    }
};

const closeDialog = () => {
    visible.value = false;
    isEdit.value = false;
    // 重置父菜单选择器
    parentMenuValue.value = [];
    // 重置表单
    if (menuFormRef.value) {
        menuFormRef.value.resetFields();
    }
};

// 查看详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
    row: {} as MenuItem,
    list: [] as any[]
});

const handleView = async (row: MenuItem) => {
    try {
        loading.value = true;
        // 根据ID获取最新菜单详情
        const res = await getMenuById(row.id);
        const responseData = res as any;
        
        if (responseData && responseData.code === 200 && responseData.data) {
            const menuData = responseData.data;
            viewData.value.row = {
                ...menuData,
                isDisplay: formatDisplayStatus(menuData.isDisplay),
                status: formatStatus(menuData.status),
                createTime: formatTime(menuData.createTime),
                updateTime: formatTime(menuData.updateTime)
            };
    viewData.value.list = [
                { prop: 'id', label: '菜单ID' },
                { prop: 'parentId', label: '父菜单ID' },
                { prop: 'menuName', label: '菜单名称' },
                { prop: 'menuCode', label: '菜单编码' },
                { prop: 'url', label: '路由路径' },
                { prop: 'icon', label: '图标' },
                { prop: 'sortOrder', label: '排序' },
                { prop: 'isDisplay', label: '是否显示' },
                { prop: 'status', label: '状态' },
                { prop: 'description', label: '描述' },
                { prop: 'createTime', label: '创建时间' },
                { prop: 'updateTime', label: '更新时间' }
            ];
    visible1.value = true;
        } else {
            const errorMsg = (responseData && responseData.msg) || '获取菜单详情失败';
            ElMessage.error(errorMsg);
        }
    } catch (error) {
        console.error('获取菜单详情失败:', error);
        ElMessage.error('获取菜单详情失败，请稍后重试');
    } finally {
        loading.value = false;
    }
};

// 删除相关
const handleDelete = async (row: MenuItem) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除菜单 "${row.menuName}" 吗？`,
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );
        
        loading.value = true;
        const res = await deleteMenu(row.id);
        const responseData = res as any;
        
        if (responseData && responseData.code === 200) {
    ElMessage.success('删除成功');
            loadMenuData(); // 刷新列表
        } else {
            const errorMsg = (responseData && responseData.msg) || '删除失败';
            ElMessage.error(errorMsg);
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除菜单失败:', error);
            ElMessage.error('删除失败，请稍后重试');
        }
    } finally {
        loading.value = false;
    }
};

// 格式化显示状态
const formatDisplayStatus = (status: number) => {
    return status === 1 ? '显示' : '隐藏';
};

// 格式化状态
const formatStatus = (status: number) => {
    return status === 1 ? '启用' : '禁用';
};

// 验证Element Plus图标是否有效
const isValidElementIcon = (iconName: string) => {
    if (!iconName) return false;
    
    // 检查是否为Element Plus图标
    return iconName in ElementPlusIconsVue;
};

// 新增菜单
const handleAdd = () => {
    rowData.value = {
        id: '',
        parentId: '0',
        menuName: '',
        menuCode: '',
        url: '',
        sortOrder: 1,
        icon: '',
        isDisplay: 1,
        description: '',
        status: 1,
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: '',
        children: [],
        checked: false
    } as MenuItem;
    
    // 重置父菜单选择器为空
    parentMenuValue.value = [];
    
    isEdit.value = false;
    visible.value = true;
};

// 页面初始化
onMounted(() => {
    loadMenuData();
});
</script>

<style scoped>
.dialog-footer {
    text-align: right;
    padding: 20px 0 0 0;
}

.dialog-footer .el-button {
    margin-left: 10px;
}

:deep(.el-form-item__label) {
    font-weight: 500;
}

:deep(.el-input-number) {
    width: 100%;
}

:deep(.el-cascader) {
    width: 100%;
}

.icon-text {
    display: inline-block;
    padding: 2px 6px;
    background-color: #f5f7fa;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    font-size: 12px;
    color: #606266;
    min-width: 20px;
    text-align: center;
}

/* 图标选择器样式 */
.icon-selector {
    max-height: 500px;
    overflow-y: auto;
}

.icon-search {
    margin-bottom: 20px;
    text-align: center;
}

.icon-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 10px;
    max-height: 400px;
    overflow-y: auto;
}

.icon-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 15px 10px;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s;
    background-color: #fff;
}

.icon-item:hover {
    border-color: #409eff;
    background-color: #f0f9ff;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.icon-item.active {
    border-color: #409eff;
    background-color: #e6f7ff;
    color: #409eff;
}

.icon-item .icon-name {
    margin-top: 8px;
    font-size: 12px;
    color: #666;
    text-align: center;
    word-break: break-all;
    line-height: 1.2;
}

.icon-item.active .icon-name {
    color: #409eff;
    font-weight: 500;
}

/* 滚动条样式 */
.icon-grid::-webkit-scrollbar {
    width: 6px;
}

.icon-grid::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.icon-grid::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

.icon-grid::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}
</style>